package org.gdpu.util;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import org.apache.logging.log4j.LogManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-6-10
 * Time: 下午12:11
 * To change this template use File | Settings | File Templates.
 */
@Service
@Transactional
public class WordUtil {
    private ActiveXComponent wordApp = new ActiveXComponent("Word.Application"); // 启动word
    private Dispatch docs = wordApp.getProperty("Documents").toDispatch();
    private Dispatch document = Dispatch.call(docs, "Add").toDispatch();
    private Dispatch selection = Dispatch.get(wordApp, "Selection").toDispatch();
    private Dispatch align = Dispatch.get(selection, "ParagraphFormat").toDispatch();
    private Dispatch font = Dispatch.get(selection, "Font").toDispatch();
    private final static org.apache.logging.log4j.Logger logger = LogManager.getLogger(WordUtil.class);
    private static Map temp = new HashMap();
    private int flag = 1;

    public void wordToTitle(){
        Dispatch.put(align, "Alignment", "3");
        Dispatch.put(font, "Bold", new Variant(true));
        Dispatch.put(font, "Color", "0,0,0,0");
        Dispatch.put(font,"Size",new Variant(14));
        Dispatch.call(selection, "TypeText", "20__ - 20__学年第__学期        考试方式：开卷[  ] 闭卷[  ]");
        Dispatch.call(selection, "TypeParagraph");
        Dispatch.put(font,"Size",new Variant(18));
        Dispatch.call(selection,"TypeText","课程名称：") ;
        Dispatch.put(font, "Underline", new Variant(true));
        Dispatch.call(selection,"TypeText","VB程序设计    ") ;
        Dispatch.put(font, "Underline", new Variant(false));
        Dispatch.call(selection, "TypeParagraph");
        Dispatch.call(selection,"TypeText","使用班级：______________");
        Dispatch.call(selection, "TypeParagraph");
        Dispatch.call(selection,"TypeText","班级：_________  学号：_________  姓名：_________ ");
        Dispatch.call(selection, "TypeParagraph");

    }

    public void setHeaderText(String imgPath){
        Dispatch activeWindow = Dispatch.get(wordApp, "ActiveWindow").toDispatch();
        Dispatch view = Dispatch.get(activeWindow, "View").toDispatch();
        //对象9表示页眉 对象10表示页脚
        Dispatch.put(view, "SeekView", new Variant(9));
        Dispatch.put(font, "Bold", new Variant(true));
        Dispatch.put(font, "Size", 20);
        Dispatch image = Dispatch.get(selection, "InLineShapes").toDispatch();
        Dispatch.call(image, "AddPicture", imgPath);
        Dispatch.call(selection, "TypeText"," 试题、试卷纸       (  )卷");
        Dispatch.put(view, "SeekView", new Variant(0)); //wdSeekMainDocument-0恢复视图;
    }

    public void wordToSecondTitle(String category,String score,String num){
        Dispatch.put(align, "Alignment", "3");
        Dispatch.put(font, "Bold", new Variant(true));
        Dispatch.put(font,"Size",new Variant(16));
        if(flag>2)
            Dispatch.call(selection, "TypeParagraph");
        Dispatch.call(selection, "TypeText", temp.get(flag)+"、"+category+"（"+num+"×"+score+"分）");
        Dispatch.call(selection, "TypeParagraph");
        ++flag;
    }

    public void wordToInput(String str,int num){
        Dispatch.put(font,"Bold",new Variant(false));
        Dispatch.put(font,"Size",new Variant(12));
        str = str.replaceAll("[\\t\\n\\r\\s\\f]","");
        Dispatch.call(selection, "TypeText",num+"、"+str);
        Dispatch.call(selection, "TypeParagraph");
    }

    public void wordToChoice(String str,int num){
        Dispatch.put(font,"Bold",new Variant(false));
        Dispatch.put(font,"Size",new Variant(12));

        int flag;
        int answerLength=0;
        int i = 65;	//A字符
        List<Integer> index = new ArrayList<Integer>();
        str = str.replace("(","（");
        str = str.replace(")","）");
        str = str.replaceAll("[\\t\\n\\r\\s\\f]","");
        if(str.indexOf("（"+(char)i+"）")>0){
            while(str.indexOf((char)i+"）")>0){
                index.add(str.indexOf((char)i+"）"));
                ++i;
            }
            flag = 1;	//格式1
        }
        else{
            while(str.indexOf((char)i+"）")>0){
                index.add(str.indexOf((char)i+"）"));
                ++i;
            }
            while(str.indexOf((char)i+"、")>0){
                index.add(str.indexOf((char)i+"、"));
                ++i;
            }
            flag = 2;	//格式2
        }
        String input[] = new String[index.size()+1];
        if(flag == 1){
            input[0] = str.substring(0,index.get(0)-1);
            Dispatch.call(selection, "TypeText",num+"、"+input[0]);
            Dispatch.call(selection, "TypeParagraph");
            for(i = 1;i<index.size()+1;i++){
                if(i==index.size())
                    input[i] = str.substring(index.get(i-1)-1);
                else
                    input[i] = str.substring(index.get(i-1)-1,index.get(i)-1);
            }
            answerLength = str.length()-input[0].length();
        }
        if(flag == 2){
            input[0] = str.substring(0,index.get(0));
            Dispatch.call(selection, "TypeText",num+"、"+input[0]);
            Dispatch.call(selection, "TypeParagraph");
            for(i = 1;i<index.size()+1;i++){
                if(i==index.size())
                    input[i] = str.substring(index.get(i-1)+2);
                else
                    input[i] = str.substring(index.get(i-1)+2,index.get(i));
                input[i] = "（"+(char)(64+i)+"）"+input[i];
            }
            answerLength = str.length()-input[0].length()+input.length-1;
    }
        Dispatch.put(font,"Size",new Variant(11));
        if(answerLength<=38){
            for(i=1;i<input.length;i++){
                Dispatch.call(selection, "TypeText",input[i]+" ");
            }
            Dispatch.call(selection, "TypeParagraph");
            Dispatch.call(selection, "TypeParagraph");
        }
        else{
            for(i=1;i<input.length;i++){
                Dispatch.call(selection, "TypeText",input[i]+" ");
                Dispatch.call(selection, "TypeParagraph");
            }
            Dispatch.call(selection, "TypeParagraph");
        }
    }

    public void wordToAnswerByChoiceOrJudge(String str,int num){
        Dispatch.put(font,"Bold",new Variant(false));
        Dispatch.put(font,"Size",new Variant(16));
        Dispatch.call(selection, "TypeText",num+"、"+str+"    ");
        if(num % 5 == 0){
            Dispatch.call(selection, "TypeParagraph");
        }
    }

    public void wordToLine(){
        Dispatch.call(selection, "TypeParagraph");
    }

    public void wordToAnswer(String str,int num){
        Dispatch.put(font,"Bold",new Variant(false));
        Dispatch.put(font,"Size",new Variant(16));
        Dispatch.call(selection, "TypeText",num+"、"+str);
        Dispatch.call(selection, "TypeParagraph");
    }

    public void saveWord(String toPath){
        Dispatch.call(document, "SaveAs", toPath);
        Dispatch.call(document, "Close",new Variant(true));
        wordApp.invoke("Quit", new Variant[]{});
    }

    public void saveWordAnswer(String toPath){
        Dispatch.call(document, "SaveAs", toPath);
        Dispatch.call(document, "Close",new Variant(true));
        wordApp.invoke("Quit", new Variant[]{});
        ComThread.Release();
    }

    public void wordConverter(String inPath,String toPath,int convertNum) {
        ActiveXComponent axc = new ActiveXComponent("Word.Application");
        try {
            //设置word不可见
            axc.setProperty("Visible",new Variant(false));
            Dispatch docs = axc.getProperty("Documents").toDispatch();
            Dispatch doc = Dispatch.invoke(docs,"Open",Dispatch.Method,new Object[]{inPath,new Variant(false),
                    new Variant(true)},new int[1]).toDispatch();
            //对象8表示WordToHtml 17表示WordToPdf
            Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {
                    toPath, new Variant(convertNum) }, new int[1]);
            Variant f = new Variant(false);
            Dispatch.call(doc, "Close", f);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
        } finally{
            axc.invoke("Quit", new Variant[] {});
            ComThread.Release();
        }
    }

    public void setNum(){
        temp.put(1,"一");
        temp.put(2,"二");
        temp.put(3,"三");
        temp.put(4,"四");
        temp.put(5,"五");
    }

}
